package vn.com.vhc.json;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;

public class WebserviceHelper {
	
		private static String URL = "http://10.0.2.2/BabyLove-core/";
		
		static InputStream is = null;
	    static JSONObject jObj = null;
	    static String json = "";
		
		@SuppressLint("NewApi")
		public static String getDataFromUrl(ArrayList<NameValuePair> parameters, String filename){
			String result = "";
			try{
				//Create a HTTP Client
				HttpClient httpclient = new DefaultHttpClient();
				
				//Create and object to Post values to the server
				//The url is specified in the Constants class to increase modifiability
				String html = URL + filename;
				HttpPost httppost = new HttpPost(URL + filename);
				
				//Set the attributes to be posted as Parameters
				httppost.setEntity(new UrlEncodedFormEntity(parameters));
				
				StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
				StrictMode.setThreadPolicy(policy); 
				
				//Execute the post and get the response
				HttpResponse response = httpclient.execute(httppost);
				
				//Get the response as ans entity
				HttpEntity entity = response.getEntity();
				
				//Get the content of the response as a stream
				InputStream stream=entity.getContent();
				
				//Convert the stream to a GSON object
		        result= convertStreamToString(stream);
		         
			}catch(Exception e){
				Log.e("PHP Client", "Error in http connection"+e.toString());
				return e.toString();
			}
	        return result;
		}
		
		//Convert an inputstream to a string
		public static String convertStreamToString(InputStream is) 
	    {
	    	BufferedReader reader = new BufferedReader(new InputStreamReader(is));
	    	StringBuilder sb = new StringBuilder();
	    	
	    	String line = null;
	    	try {
	    		while ((line = reader.readLine()) != null) {
	    			sb.append(line + "\n");
	    		}
	    	} 
	    	catch (IOException e) {
	    		Log.e("PHP Client","Error : "+e.getMessage());
	    	} 
	    	finally {
	    		try {
	    			is.close();
	    		} catch (IOException e1) {
	    			Log.e("PHP Client","Error : "+e1.getMessage());
	    		}
	    	}
	    	return sb.toString();
	    }
		
		
		public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
		 
	        // Making HTTP request
	        try {
	            // defaultHttpClient
	        	HttpClient  httpClient = new DefaultHttpClient();
	            HttpPost httpPost = new HttpPost(url);
	            httpPost.setEntity(new UrlEncodedFormEntity(params));
	 
	            HttpResponse httpResponse = httpClient.execute(httpPost);
	            HttpEntity httpEntity = httpResponse.getEntity();
	            is = httpEntity.getContent();
	 
	        } catch (UnsupportedEncodingException e) {
	            e.printStackTrace();
	        } catch (ClientProtocolException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	 
	        try {
	            BufferedReader reader = new BufferedReader(new InputStreamReader(
	                    is, "UTF-8"), 8);
	            StringBuilder sb = new StringBuilder();
	            sb.append(reader.readLine() + "\n");
	            String line = "0";
	            while ((line = reader.readLine()) != null) {
	                sb.append(line + "\n");
	            }
	            is.close();
	            json = sb.toString();
	            Log.e("JSON", json);
	        } catch (Exception e) {
	            Log.e("Buffer Error", "Error converting result " + e.toString());
	        }
	 
	        // try parse the string to a JSON object
	        try {
	            jObj = new JSONObject(json);
	        } catch (JSONException e) {
	            Log.e("JSON Parser", "Error parsing data " + e.toString());
	        }
	 
	        // return JSON String
	        return jObj;
	 
	    }
}
